//
//  AddWeatherViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/25.
//

import UIKit
import ReactiveCocoa
import SVProgressHUD

class AddWeatherViewController: UIViewController,JDFlowLayoutDelegate {
    
    @IBOutlet weak var helloLabel: UILabel!
    @IBOutlet weak var dateBtn: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionPageController: UIPageControl!
    @IBOutlet weak var changeDayBtn: UIButton!
    @IBOutlet weak var addBtn: UIButton!
    @IBOutlet weak var timeView: UIView!
    
    var isToday = true
    
    var selectDateTimeStamp: String?
    var nextTimeStamp: String?
    
    var selectIndexPath: IndexPath?
    
    let weatherArray = ["晴天", "多云", "阴天", "雨", "雪", "雾", "浮尘", "沙尘暴", "夜_晴", "夜_多云","夜_雾霾","夜_下雨","夜_下雪","夜_打雷","白_多云雷","白_多云有风","白_雷雨","夜_多云有风","夜_风","夜_雷雨","白_日落","白_有风","",""]
    
    var diaryModel: DiaryModel?
    
    var selectYear: Int = Int(NSString.currentYear()) ?? 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        nextTimeStamp = NSString.currentTimeStamp()
        
        diaryModel = DiaryModel()

        helloLabel.text = NSString.getChineseHourDescription() + "好"
        
        addBtn.layer.borderWidth = 0.5
        addBtn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
        addBtn.layer.cornerRadius = addBtn.height * 0.5
        addBtn.layer.masksToBounds = true
        
        let flowLayout = JDFlowLayout()
        flowLayout.rowCount = 2
        flowLayout.itemCountPerRow = 3
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 25.0, bottom: 25.0, right: 25.0)
//        if (isFullScreen) {
//            flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 25.0, bottom: 25.0, right: 25.0)
//        } else {
//            flowLayout.sectionInset = UIEdgeInsets(top: 25.0, left: 25.0, bottom: 25.0, right: 25.0)
//        }
        let margin = 25.0
        let itemLength = (Double(collectionView.width) - margin * 4) / 3 - 2.0
        flowLayout.itemSize = CGSize(width: itemLength, height: itemLength)
        flowLayout.minimumLineSpacing = 25.0
        flowLayout.scrollDirection = .horizontal
        flowLayout.pageDelegate = self
        collectionView.collectionViewLayout = flowLayout
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "AddWeatherCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "AddWeatherCollectionViewCell")
        
        collectionPageController.numberOfPages = (weatherArray.count-1)/6+1
        collectionPageController.currentPage = 0
        
        if selectDateTimeStamp == nil {
            setDateBtn()
        } else {
            isToday = false
            
            addBtn.setTitle("记录这天的心情", for: .normal)
            changeDayBtn.setTitle("记录今天", for: .normal)
            changeDayBtn.setImage(UIImage(named: "下一个"), for: .normal)
            changeDayBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 90.0, bottom: 0, right: 0)
            
            setDateBtn(timeStamp: selectDateTimeStamp)
        }
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "关闭"), style: .plain, target: self, action: #selector(closeAction))
        
        let tap = UITapGestureRecognizer()
        tap.rac_gestureSignal()?.subscribeNext({ [weak self] (_) in
            self?.tapAction()
        })
        timeView.addGestureRecognizer(tap)
    }
    
    // 友盟页面统计
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        MobClick.beginLogPageView("添加天气")
        MobClick.event("pages_num", attributes: ["TianJiaTianQi":"进入添加天气"])
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("添加天气")
        MobClick.event("pages_num", attributes: ["TianJiaTianQi":"离开添加天气"])
    }
    
    func currentPage(forFlowLaout page: Int) {
        
        collectionPageController.currentPage = page
    }
    
    func jdCollectionView(_ jdCollectionView: UICollectionView, didSelecteItemAt indexPath: IndexPath) {
        
        selectIndexPath = indexPath
        
        collectionView.reloadData()
        
        addBtn.isEnabled = true
        addBtn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
    }
    
}

extension AddWeatherViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//
//        let margin = 25.0
//        let itemLength = (Double(collectionView.width) - margin * 4) / 3 - 2.0
//
//        return CGSize(width: itemLength, height: itemLength)
//    }
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 25.0 }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 0.01 }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { weatherArray.count }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: AddWeatherCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddWeatherCollectionViewCell", for: indexPath) as! AddWeatherCollectionViewCell
        cell.imgV.image = UIImage(named: weatherArray[indexPath.row])
        
        if indexPath.row > 21 {
            cell.shouldShow = false
        } else {
            cell.shouldShow = true
        }
        
        if selectIndexPath == indexPath {
            cell.isSelectCell = true
        } else {
            cell.isSelectCell = false
        }
        
        return cell
    }
    
    
   
}

extension AddWeatherViewController {
    
    @objc func closeAction() {
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func changeDayAction() {
        
        selectDateTimeStamp = nil
        
        if isToday == true {
            isToday = false
            
            addBtn.setTitle("记录昨天的心情", for: .normal)
            changeDayBtn.setTitle("记录今天", for: .normal)
            changeDayBtn.setImage(UIImage(named: "下一个"), for: .normal)
            changeDayBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 90.0, bottom: 0, right: 0)
        } else {
            isToday = true
            
            addBtn.setTitle("记录今天的心情", for: .normal)
            changeDayBtn.setTitle(" 记录昨天", for: .normal)
            changeDayBtn.setImage(UIImage(named: "上一个"), for: .normal)
            changeDayBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        
        setDateBtn()
        
    }
    
    @IBAction func addAction() {
        
        diaryModel?.timeStampStr = nextTimeStamp
        diaryModel?.weatherStr = weatherArray[selectIndexPath?.item ?? 0]
        
        let vc = AddMoodViewController()
        vc.dayStr = ((dateBtn.currentAttributedTitle?.string ?? "") as NSString).substring(to: 2)
        vc.diaryModel = diaryModel
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension AddWeatherViewController {
    func setDateBtn(timeStamp: String? = nil) {
        
        selectYear = Int(NSString.getYear(timeStamp ?? "")) ?? 0
        
        if selectYear == 0 {
            selectYear = Int(NSString.currentYear()) ?? 0
        }
        
        var dateTitleStr = ""
        
        if timeStamp != nil {
            dateTitleStr = "这天 " + NSString.convertTimeStamp(toMH: timeStamp!) + " " + NSString.dateWeek(withTimeStamp: timeStamp!)
            nextTimeStamp = timeStamp
        } else if isToday == true {
            let timeStamp = NSString.currentTimeStamp()
            dateTitleStr = "今天 " + NSString.currentMonthAndDay() + " " + NSString.dateWeek(withTimeStamp: timeStamp)
            nextTimeStamp = timeStamp
        } else {
            guard var timeStamp: Int = Int(NSString.currentTimeStamp()) else { return }
            timeStamp -= 24 * 60 * 60
            dateTitleStr = "昨天 " + NSString.monthAndDay("\(timeStamp)") + " " + NSString.dateWeek(withTimeStamp: "\(timeStamp)")
            nextTimeStamp = "\(timeStamp)"
        }
        
        let mString = NSMutableAttributedString(string: dateTitleStr)
        mString.setAttributes([.font: UIFont.systemFont(ofSize: 14.0, weight: .medium)], range: NSMakeRange(0, 2))
        
        dateBtn.setAttributedTitle(mString, for: .normal)
        dateBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 200.0, bottom: 0, right: 0)
        dateBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -10.0, bottom: 0, right: 0)
    }
    
}

extension AddWeatherViewController {
    
    @objc func tapAction() {
        
        let pickerView = UIPickerView(frame: CGRect(x: 0, y: 70.0, width: 260.0, height: 240.0))
        pickerView.delegate = self
        pickerView.dataSource = self
        
        DispatchQueue.main.async { [weak self] in
            
            guard let self = self else { return }
            
            var day2 = 0
            
            var currentYear: Int = Int(NSString.currentYear()) ?? 0
            
            if self.selectDateTimeStamp != nil {
                currentYear = Int(NSString.getYear(self.selectDateTimeStamp!)) ?? 0
            }
            
            if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) {
                day2 += 29
            } else {
                day2 += 28
            }
            
            var days = 0
            
            var currentMonth: Int = Int(NSString.currentMonth()) ?? 0
            var currentDay: Int = Int(NSString.currentDay()) ?? 0
            
            if self.selectDateTimeStamp != nil {
                currentMonth = Int(NSString.getMonth(self.selectDateTimeStamp!)) ?? 0
                currentDay = Int(NSString.getDay(self.selectDateTimeStamp!)) ?? 0
            }
            
            switch currentMonth {
            case 1:
                days = currentDay
            case 2:
                days = 31 + currentDay
            case 3:
                days = 31 + day2 + currentDay
            case 4:
                days = 31 + day2 + 31 + currentDay
            case 5:
                days = 31 + day2 + 31 + 30 + currentDay
            case 6:
                days = 31 + day2 + 31 + 30 + 31 + currentDay
            case 7:
                days = 31 + day2 + 31 + 30 + 31 + 30 + currentDay
            case 8:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + currentDay
            case 9:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + currentDay
            case 10:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + currentDay
            case 11:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + currentDay
            case 12:
                days = 31 + day2 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + currentDay
            default:
                break
            }
            
            if currentYear == Int(NSString.currentYear()) ?? 0 {
                pickerView.selectRow(0, inComponent: 0, animated: false)
            } else {
                pickerView.selectRow(1, inComponent: 0, animated: false)
            }
            
            pickerView.selectRow(days - 1, inComponent: 1, animated: false)
        }
        
        let alertC = UIAlertController(title: "提示", message: "请选择时间\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
        alertC.view.addSubview(pickerView)
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak self] (_) in
            let selectRow1 = pickerView.selectedRow(inComponent: 1)
            let selectRow0 = pickerView.selectedRow(inComponent: 0)
            
            let currentSelectYear = selectRow0 == 0 ? NSString.currentYear() : "\(Int(NSString.currentYear())! - 1)"
            let monthDayStr: String = self?.getMonthAndDay(row: selectRow1) ?? ""
            let timeStr = "\(currentSelectYear)" + "年" + monthDayStr + " " + NSString.currentHour() + ":" + NSString.currentMinute() + ":" + NSString.currentSecond()
            let timeStamp = NSString.convertTime(toTimeStamp2: timeStr)
            
            print(timeStr)
            print(timeStamp)
            
            if timeStamp > NSString.currentTimeStamp() {
                SVProgressHUD.showError(withStatus: "不可以选择今天之后的日期")
                SVProgressHUD.dismiss(withDelay: 2.0)
                return
            }
            
            self?.selectDateTimeStamp = timeStamp
            self?.setDateBtn(timeStamp: timeStamp)
            
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .destructive, handler: { (_) in
            
        }))
        present(alertC, animated: true, completion: nil)
        
    }
    
}

extension AddWeatherViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 { return 2 }
        
        var days = 31 + 0 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31
        
        if (selectYear % 100 == 0 && selectYear % 400 == 0) || (selectYear % 100 != 0 && selectYear % 4 == 0) {
            days += 29
        } else {
            days += 28
        }
        
        return days
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let yearStr = NSString.currentYear()
        let yearInt = Int(yearStr) ?? 0
        selectYear = row == 0 ? yearInt : yearInt - 1
        
        if component == 0 {
            pickerView.reloadComponent(1)
        }
        
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            let yearStr = NSString.currentYear()
            let yearInt = Int(yearStr)
            if row == 1 {
                return "\((yearInt ?? 1) - 1)年"
            }
            return "\(yearInt ?? 0)年"
        }
        return getMonthAndDay(row: row)
    }
}

extension AddWeatherViewController {
    
    func getMonthAndDay(row: Int) -> String {
        
        var days = 0
        
        if (selectYear % 100 == 0 && selectYear % 400 == 0) || (selectYear % 100 != 0 && selectYear % 4 == 0) {
            days += 29
        } else {
            days += 28
        }
        
        var prefixStr = ""
        
        if row < 31 {
            prefixStr = "01月" + String(format: "%02d日", row + 1)
        } else if row < 31 + days {
            prefixStr = "02月" + String(format: "%02d日", row + 1 - 31)
            
            print("prefixStr === \(prefixStr)")
            
        } else if row < 31 + days + 31 {
            prefixStr = "03月" + String(format: "%02d日", row + 1 - 31 - days)
        } else if row < 31 + days + 31 + 30 {
            prefixStr = "04月" + String(format: "%02d日", row + 1 - 31 - days - 31)
        } else if row < 31 + days + 31 + 30 + 31 {
            prefixStr = "05月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30)
        } else if row < 31 + days + 31 + 30 + 31 + 30 {
            prefixStr = "06月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 {
            prefixStr = "07月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 {
            prefixStr = "08月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 {
            prefixStr = "09月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 {
            prefixStr = "10月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31 - 30)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 {
            prefixStr = "11月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31 - 30 - 31)
        } else if row < 31 + days + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 {
            prefixStr = "12月" + String(format: "%02d日", row + 1 - 31 - days - 31 - 30 - 31 - 30 - 31 - 31 - 30 - 31 - 30)
        }
        return prefixStr
    }

}

